package com.booking.springrestful.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booking.springrestful.domain.Counselors;
import com.booking.springrestful.domain.Feedback;
import com.booking.springrestful.domain.Users;
import com.booking.springrestful.domain.dto.FeedbackDto;
import com.booking.springrestful.domain.vo.CounselorsVo;
import com.booking.springrestful.domain.vo.FeedbackVo;
import com.booking.springrestful.exception.BusinessException;
import com.booking.springrestful.mapper.*;
import com.booking.springrestful.resp.PageResult;
import com.booking.springrestful.resp.ResultCodeEnum;
import com.booking.springrestful.service.FeedbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
* @author 13182
* @description 针对表【feedback(来访者反馈打分表)】的数据库操作Service实现
* @createDate 2024-11-05 21:11:32
*/
@Service
@Slf4j
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback>
    implements FeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private CounselorsMapper counselorsMapper;

    @Resource
    private AppointmentsMapper appointmentsMapper;

    @Override
    public List<CounselorsVo> getAllCounselor() {
        List<Users> usersList = usersMapper.selectList(new QueryWrapper<Users>().eq("status", '1').eq("userType","counselor"));
        List<CounselorsVo> counselorsVos = new ArrayList<>();

        usersList.forEach(item -> {
            CounselorsVo counselorsVo = new CounselorsVo();
            counselorsVo.setRealname(item.getRealname());

            if (counselorsMapper.exists(new QueryWrapper<Counselors>().eq("userId", item.getUserid()))){
                Counselors counselors = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("userId", item.getUserid()));
                counselorsVo.setCounselorId(counselors.getCounselorid());
            }

            counselorsVos.add(counselorsVo);
        });
        return counselorsVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitFeedback(Feedback feedback) {
        if (feedback.getContent().isEmpty()){
            throw new BusinessException(ResultCodeEnum.INTERNAL_SERVER_ERROR,"未填写主观反馈");
        }
        feedback.setUpdatedat(feedback.getCreatedat());
        feedbackMapper.insert(feedback);

        //更新综合评分
        QueryWrapper<Counselors> wrapper = new QueryWrapper<Counselors>().eq("counselorId", feedback.getCounselorid());
        BigDecimal rating = counselorsMapper.selectOne(wrapper).getRating();
        if (rating != null && rating.compareTo(BigDecimal.ZERO) != 0) {
            
            List<Feedback> feedbackList = feedbackMapper.selectList(new QueryWrapper<Feedback>().eq("counselorId", feedback.getCounselorid()));
            BigDecimal totalRating = BigDecimal.ZERO; // 用于存储总评分
            int count = 0; // 用于存储有效评分的数量

            // 使用 for 循环遍历 feedbackList
            for (int i = 0; i < feedbackList.size(); i++) {
                Feedback item = feedbackList.get(i); // 获取当前项
                BigDecimal num = item.getRating(); // 获取评分

                // 判断评分不为空且大于 0
                if (num != null && num.compareTo(BigDecimal.ZERO) > 0) {
                    totalRating = totalRating.add(num); // 累加评分
                    count++; // 有效评分计数加1
                }
            }

            BigDecimal averageRating = BigDecimal.ZERO; // 初始化平均评分
            if (count > 0) {
                averageRating = totalRating.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); // 计算平均数并保留两位小数
            }
            Counselors counselors = new Counselors();
            counselors.setRating(averageRating);
            counselorsMapper.update(counselors,wrapper);
        } else {
            Counselors counselors = new Counselors();
            counselors.setRating(feedback.getRating());
            counselorsMapper.update(counselors,wrapper);
        }

    }

    @Override
    public PageResult<FeedbackVo> getFeedback(FeedbackDto feedbackDto) {

        log.info(feedbackDto.toString());
        QueryWrapper<Feedback> wrapper = new QueryWrapper<>();

        if (feedbackDto.getCounselorid() != null){
            wrapper.like("counselorId",feedbackDto.getCounselorid());
        }
        wrapper.orderByDesc("updatedAt");

        long pageSize = feedbackDto.getPageSize();
        long current = feedbackDto.getCurrent();

        IPage<Feedback> page = new Page<>(current, pageSize); // 创建分页对象

        // 进行分页查询
        IPage<Feedback> resultPage = feedbackMapper.selectPage(page, wrapper);

        IPage<FeedbackVo> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        List<FeedbackVo> voRecords = new ArrayList<>();

        resultPage.getRecords().forEach(item -> {
            FeedbackVo feedbackVo = new FeedbackVo();
            BeanUtils.copyProperties(item, feedbackVo);
            String userRealname = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", item.getUserid())).getRealname();
            Integer id = counselorsMapper.selectOne(new QueryWrapper<Counselors>().eq("counselorId", item.getCounselorid())).getUserid();
            String counselorname = usersMapper.selectOne(new QueryWrapper<Users>().eq("userId", id)).getRealname();
            feedbackVo.setCounselorname(counselorname);
            feedbackVo.setUserRealname(userRealname);
            voRecords.add(feedbackVo);
        });

        voPage.setRecords(voRecords);

        // 创建包含数据和分页信息的对象
        PageResult<FeedbackVo> pageResult = new PageResult<>();
        pageResult.setTotal(voPage.getTotal());
        pageResult.setData(voPage.getRecords());
        return pageResult;
    }

    @Override
    public Boolean isFeed(Integer id) {
        return feedbackMapper.exists(new QueryWrapper<Feedback>().eq("appointmentId", id));
    }

    @Override
    public Feedback getByAppId(Integer id) {
        return feedbackMapper.selectOne(new QueryWrapper<Feedback>().eq("appointmentId",id));
    }
}




